#include "featuredelegate.h"


#include <characterfeature.h>


#include <QComboBox>
#include <QMetaObject>
#include <QMetaEnum>


FeatureDelegate::FeatureDelegate(QObject *parent) :
    QStyledItemDelegate(parent)
{
}

QWidget *FeatureDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    if (index.column() <= 0)
    {
        return QStyledItemDelegate::createEditor(parent, option, index);
    }
    return new QComboBox(parent);
}

void FeatureDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
    QComboBox* cb = qobject_cast<QComboBox*>(editor);
    if (!cb)
    {
        QStyledItemDelegate::setEditorData(editor, index);
        return;
    }

    int offset = CharacterFeature::staticMetaObject.enumeratorOffset();
    QMetaEnum me;


    int featureIndex = index.column()-1;
    switch (featureIndex)
    {
    case CharacterFeatures::HitDie:
        me = CharacterFeature::staticMetaObject.enumerator(offset);
        break;

    case CharacterFeatures::SkillPoints:
        me = CharacterFeature::staticMetaObject.enumerator(offset+1);
        break;
    case CharacterFeatures::BaseAttack:
        me = CharacterFeature::staticMetaObject.enumerator(offset+2);
        break;

    case CharacterFeatures::FortSave:
    case CharacterFeatures::RefSave:
    case CharacterFeatures::WillSave:
        me = CharacterFeature::staticMetaObject.enumerator(offset+3);
        break;

    default:
        return;
    }


    for (int i = 0; i < me.keyCount(); i++)
    {
        cb->addItem(me.key(i), me.value(i));
    }

    QVariant currentValue = index.data(Qt::EditRole);
    int comboIndex = cb->findData(currentValue);
    if (comboIndex < 0)
    {
        return;
    }

    cb->setCurrentIndex(comboIndex);
}

void FeatureDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
{
    QComboBox* cb = qobject_cast<QComboBox*>(editor);
    if (!cb)
    {
        QStyledItemDelegate::setModelData(editor, model, index);
        return;
    }

    QVariant value = cb->itemData(cb->currentIndex());

    model->setData(index, value, Qt::EditRole);
}


